home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / ASM_TUTR.ZIP / ASMTUTOR.TXT < prev    next >
Text File  |  1984-11-27  |  73KB  |  1,695 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.                     IBM Personal Computer Assembly
  9.                          Language Tutorial
  10.  
  11.  
  12.  
  13.                           Joshua Auerbach
  14.                           Yale University
  15.                         Yale Computer Center
  16.                          175 Whitney Avenue
  17.                            P. O. Box 2112
  18.                      New Haven, Connecticut 06520
  19.  
  20.                          Installation Code YU
  21.  
  22.                  Integrated Personal Computers Project
  23.                         Communications Group
  24.                  Communications and Data Base Division
  25.  
  26.                             Session C316
  27.  
  28.  
  29.  
  30.  
  31. This talk is for people who are just getting started with the PC MACRO
  32. Assembler.  Maybe you are just contemplating doing some coding in
  33. assembler, maybe you have tried it with mixed success.  If you are here to
  34. get aimed in the right direction, to get off to a good start with the
  35. assembler, then you have come for the right reason.  I can't promise you'll
  36. get what you want, but I'll do my best.
  37.  
  38. On the other hand, if you have already turned out some working assembler
  39. code, then this talk is likely to be on the elementary side for you.  If
  40. you want to review a few basics and have no where else pressing to go, then
  41. by all means stay.
  42.  
  43.  
  44.  
  45. Why Learn Assembler?
  46. ____________________
  47. Why Learn Assembler?
  48. Why Learn Assembler?
  49. Why Learn Assembler?
  50.  
  51.  
  52. The reasons for LEARNING assembler are not the same as the reasons for
  53. USING it in a particular application.  But, we have to start with some of
  54. the reasons for using it and then I think the reasons for learning it will
  55. become clear.
  56.  
  57. First, let's dispose of a bad reason for using it.  Don't use it just
  58. because you think it is going to execute faster.  A particular sequence of
  59. ordinary bread-and-butter computations written in PASCAL, C, FORTRAN, or
  60. compiled BASIC can do the job just about as fast as the same algorithm
  61. coded in assembler.  Of course, interpretive BASIC is slower, but if you
  62. have a BASIC application which runs too slow you probably want to try com-
  63.  
  64.  
  65. IBM PC Assembly Language Tutorial                                         1
  66.  
  67.  
  68.  
  69. piling it before you think too much about translating parts of it to
  70. another language.
  71.  
  72. On the other hand, high level languages do tend to isolate you from the
  73. machine.  That is both their strength and their weakness.  Usually, when
  74. implemented on a micro, a high level language provides an escape mechanism
  75. to the underlying operating system or to the bare machine.  So, for
  76. example, BASIC has its PEEK and POKE.  But, the route to the bare machine
  77. is often a circuitous one, leading to tricky programming which is hard to
  78. follow.
  79.  
  80. For those of us working on PC's connected to SHARE-class mainframes, we are
  81. generally concerned with three interfaces:  the keyboard, the screen, and
  82. the communication line or lines.  All three of these entities raise machine
  83. dependent issues which are imperfectly addressed by the underlying operat-
  84. ing system or by high level languages.
  85.  
  86. Sometimes, the system or the language does too little for you.  For
  87. example, with the asynch adapter, the system provides no interrupt handler,
  88. no buffer, and no flow control.  The application is stuck with the respon-
  89. sibility for monitoring that port and not missing any characters, then
  90. deciding what to do with all errors.  BASIC does a reasonable job on some
  91. of this, but that is only BASIC.  Most other languages do less.
  92.  
  93. Sometimes, the system may do too much for you.  System support for the key-
  94. board is an example.  At the hardware level, all 83 keys on the keyboard
  95. send unique codes when they are pressed, held down, and released.  But,
  96. someone has decided that certain keys, like Num Lock and Scroll Lock are
  97. going to do certain things before the application even sees them and can't
  98. therefore be used as ordinary keys.
  99.  
  100. Sometimes, the system does about the right amount of stuff but does it less
  101. efficiently then it should.  System support for the screen is in this
  102. class.  If you use only the official interface to the screen you sometimes
  103. slow your application down unacceptably.  I said before, don't use assem-
  104. bler just to speed things up, but there I was talking about mainline code,
  105. which generally can't be speeded up much by assembler coding.  A critical
  106. system interface is a different matter:  sometimes we may have to use
  107. assembler to bypass a hopelessly inefficient implementation.  We don't want
  108. to do this if we can avoid it, but sometimes we can't.
  109.  
  110. Assembly language code can overcome these deficiencies.  In some cases, you
  111. can also overcome these deficiencies by judicious use of the escape valves
  112. which your high level language provides.  In BASIC, you can PEEK and POKE
  113. and INP and OUT your way around a great many issues.  In many other lan-
  114. guages you can issue system calls and interrupts and usually manage, one
  115. way or other, to modify system memory.  Writing handlers to take real-time
  116. hardware interrupts from the keyboard or asynch port, though, is still
  117. going to be a problem in most languages.  Some languages claim to let you
  118. do it but I have yet to see an acceptably clean implementation done that
  119. way.
  120.  
  121. The real reason while assembler is better than "tricky POKEs" for writing
  122. machine-dependent code, though, is the same reason why PASCAL is better
  123. than assembler for writing a payroll package:  it is easier to maintain.
  124.  
  125.  
  126. IBM PC Assembly Language Tutorial                                         2
  127.  
  128.  
  129.  
  130. Let the high level language do what it does best, but recognize that there
  131. are some things which are best done in assembler code.  The assembler,
  132. unlike the tricky POKE, can make judicious use of equates, macros, labels,
  133. and appropriately placed comments to show what is really going on in this
  134. machine-dependent realm where it thrives.
  135.  
  136. So, there are times when it becomes appropriate to write in assembler; giv-
  137. en that, if you are a responsible programmer or manager, you will want to
  138. be "assembler-literate" so you can decide when assembler code should be
  139. written.
  140.  
  141. What do I mean by "assembler-literate?"  I don't just mean understanding
  142. the 8086 architecture; I think, even if you don't write much assembler code
  143. yourself, you ought to understand the actual process of turning out assem-
  144. bler code and the various ways to incorporate it into an application.  You
  145. ought to be able to tell good assembler code from bad, and appropriate
  146. assembler code from inappropriate.
  147.  
  148.  
  149.  
  150. Steps to becoming ASSEMBLER-LITERATE
  151. ____________________________________
  152. Steps to becoming ASSEMBLER-LITERATE
  153. Steps to becoming ASSEMBLER-LITERATE
  154. Steps to becoming ASSEMBLER-LITERATE
  155.  
  156.  
  157. 1.  Learn the 8086 architecture and most of the instruction set.  Learn
  158.     what you need to know and ignore what you don't.  Reading:  The 8086
  159.     Primer by Stephen Morse, published by Hayden.  You need to read only
  160.     two chapters, the one on machine organization and the one on the
  161.     instruction set.
  162.  
  163. 2.  Learn about a few simple DOS function calls.  Know what services the
  164.     operating system provides.  If appropriate, learn a little about other
  165.     systems too.  It will aid portability later on.  Reading:  appendices D
  166.     and E of the PC DOS manual.
  167.  
  168. 3.  Learn enough about the MACRO assembler and the LINKer to write some
  169.     simple things that really work.  Here, too, the main thing is figuring
  170.     out what you don't need to know.  Whatever you do, don't study the sam-
  171.     ple programs distributed with the assembler unless you have nothing
  172.     better!
  173.  
  174. 4.  At the same time as you are learning the assembler itself, you will
  175.     need to learn a few tools and concepts to properly combine your assem-
  176.     bler code with the other things you do.  If you plan to call assembler
  177.     subroutines from a high level language, you will need to study the
  178.     interface notes provided in your language manual.  Usually, this forms
  179.     an appendix of some sort.  If you plan to package your assembler rou-
  180.     tines as .COM programs you will need to learn to do this.  You should
  181.     also learn to use DEBUG.
  182.  
  183. 5.  Read the Technical Reference, but very selectively.  The most important
  184.     things to know are the header comments in the BIOS listing.  Next, you
  185.     will want to learn about the RS 232 port and maybe about the video
  186.     adapters.
  187.  
  188.  
  189.  
  190.  
  191. IBM PC Assembly Language Tutorial                                         3
  192.  
  193.  
  194.  
  195. Notice that the key thing in all five phases is being selective.  It is
  196. easy to conclude that there is too much to learn unless you can throw away
  197. what you don't need.  Most of the rest of this talk is going to deal with
  198. this very important question of what you need and don't need to learn in
  199. each phase.  In some cases, I will have to leave you to do almost all of
  200. the learning, in others, I will teach a few salient points, enough, I hope,
  201. to get you started.  I hope you understand that all I can do in an hour is
  202. get you started on the way.
  203.  
  204.  
  205.  
  206. Phase 1:  Learn the architecture and instruction set
  207. ____________________________________________________
  208. Phase 1:  Learn the architecture and instruction set
  209. Phase 1:  Learn the architecture and instruction set
  210. Phase 1:  Learn the architecture and instruction set
  211.  
  212.  
  213. The Morse book might seem like a lot of book to buy for just two really
  214. important chapters; other books devote a lot more space to the instruction
  215. set and give you a big beautiful reference page on each instruction.  And,
  216. some of the other things in the Morse book, although interesting, really
  217. aren't very vital and are covered too sketchily to be of any real help.
  218. The reason I like the Morse book is that you can just read it; it has a
  219. very conversational style, it is very lucid, it tells you what you really
  220. need to know, and a little bit more which is by way of background; because
  221. nothing really gets belabored to much, you can gracefully forget the things
  222. you don't use.  And, I very much recommend READING Morse rather than study-
  223. ing it.  Get the big picture at this point.
  224.  
  225. Now, you want to concentrate on those things which are worth fixing in mem-
  226. ory.  After you read Morse, you should relate what you have learned to this
  227. outline.
  228.  
  229. 1.  You want to fix in your mind the idea of the four segment registers
  230.     CODE, DATA, STACK, and EXTRA.  This part is pretty easy to grasp.  The
  231.     8086 and the 8088 use 20 bit addresses for memory, meaning that they
  232.     can address up to 1 megabyte of memory.  But, the registers and the
  233.     address fields in all the instructions are no more that 16 bits long.
  234.     So, how to address all of that memory?  Their solution is to put
  235.     together two 16 bit quantities like this:
  236.  
  237.       calculation  SSSS0   ---- value in the relevant segment register SHL 4
  238.       depicted in   AAAA   ---- apparent address from register or instruction
  239.       hexadecimal --------
  240.                    RRRRR   ---- real address placed on address bus
  241.  
  242.     In other words, any time memory is accessed, your program will supply a
  243.     sixteen bit address.  Another sixteen bit address is acquired from a
  244.     segment register, left shifted four bits (one nibble) and added to it
  245.     to form the real address.  You can control the values in the segment
  246.     registers and thus access any part of memory you want.  But the segment
  247.     registers are specialized:  one for code, one for most data accesses,
  248.     one for the stack (which we'll mention again) and one "extra" one for
  249.     additional data accesses.
  250.  
  251.     Most people, when they first learn about this addressing scheme become
  252.     obsessed with converting everything to real 20 bit addresses.  After a
  253.     while, though, you get use to thinking in segment/offset form.  You
  254.  
  255.  
  256. IBM PC Assembly Language Tutorial                                         4
  257.  
  258.  
  259.  
  260.     tend to get your segment registers set up at the beginning of the pro-
  261.     gram, change them as little as possible, and think just in terms of
  262.     symbolic locations in your program, as with any assembly language.
  263.  
  264.       EXAMPLE:
  265.            MOV  AX,DATASEG
  266.            MOV  DS,AX          ;Set value of Data segment
  267.            ASSUME DS:DATASEG   ;Tell assembler DS is usable
  268.            .......
  269.            MOV  AX,PLACE       ;Access storage symbolically by 16 bit address
  270.  
  271.     In the above example, the assembler knows that no special issues are
  272.     involved because the machine generally uses the DS register to complete
  273.     a normal data reference.
  274.  
  275.     If you had used ES instead of DS in the above example, the assembler
  276.     would have known what to do, also.  In front of the MOV instruction
  277.     which accessed the location PLACE, it would have placed the ES segment
  278.     prefix.  This would tell the machine that ES should be used, instead of
  279.     DS, to complete the address.
  280.  
  281.     Some conventions make it especially easy to forget about segment regis-
  282.     ters.  For example, any program of the COM type gets control with all
  283.     four segment registers containing the same value.  This program exe-
  284.     cutes in a simplified 64K address space.  You can go outside this
  285.     address space if you want but you don't have to.
  286.  
  287. 2.  You will want to learn what other registers are available and learn
  288.     their personalities:
  289.  
  290.        AX and DX are general purpose registers.  They become special only
  291.         when accessing machine and system interfaces.
  292.  
  293.        CX is a general purpose register which is slightly specialized for
  294.         counting.
  295.  
  296.        BX is a general purpose register which is slightly specialized for
  297.         forming base-displacement addresses.
  298.  
  299.        AX-DX can be divided in half, forming AH, AL, BH, BL, CH, CL, DH,
  300.         DL.
  301.  
  302.        SI and DI are strictly 16 bit.  They can be used to form indexed
  303.         addresses (like BX) and they are also used to point to strings.
  304.  
  305.        SP is hardly ever manipulated.  It is there to provide a stack.
  306.  
  307.        BP is a manipulable cousin to SP.  Use it to access data which has
  308.         been pushed onto the stack.
  309.  
  310.        Most sixteen bit operations are legal (even if unusual) when per-
  311.         formed in SI, DI, SP, or BP.
  312.  
  313.  
  314.  
  315.  
  316.  
  317. IBM PC Assembly Language Tutorial                                         5
  318.  
  319.  
  320.  
  321. 3.  You will want to learn the classifications of operations available
  322.     WITHOUT getting hung up in the details of how 8086 opcodes are con-
  323.     structed.
  324.  
  325.     8086 opcodes are complex.  Fortunately, the assembler opcodes used to
  326.     assemble them are simple.  When you read a book like Morse, you will
  327.     learn some things which are worth knowing but NOT worth dwelling on.
  328.  
  329.     a.  8086 and 8088 instructions can be broken up into subfields and bits
  330.         with names like R/M, MOD, S and W. These parts of the instruction
  331.         modify the basic operation in such ways as whether it is 8 bit or
  332.         16 bit, if 16 bit, whether all 16 bits of the data are given,
  333.         whether the instruction is register to register, register to
  334.         memory, or memory to register, for operands which are registers,
  335.         which register, for operands which are memory, what base and index
  336.         registers should be used in finding the data.
  337.  
  338.     b.  Also, some instructions are actually represented by several differ-
  339.         ent machine opcodes depending on whether they deal with immediate
  340.         data or not, or on other issues, and there are some expedited forms
  341.         which assume that one of the arguments is the most commonly used
  342.         operand, like AX in the case of arithmetic.
  343.  
  344.     There is no point in memorizing any of this detail; just distill the
  345.     bottom line, which is, what kinds of operand combinations EXIST in the
  346.     instruction set and what kinds don't.  If you ask the assembler to ADD
  347.     two things and the two things are things for which there is a legal ADD
  348.     instruction somewhere in the instruction set, the assembler will find
  349.     the right instruction and fill in all the modifier fields for you.
  350.  
  351.     I guess if you memorized all the opcode construction rules you might
  352.     have a crack at being able to disassemble hex dumps by eye, like you
  353.     may have learned to do somewhat with 370 assembler.  I submit to you
  354.     that this feat, if ever mastered by anyone, would be in the same class
  355.     as playing the "Minute Waltz" in a minute; a curiosity only.
  356.  
  357.     Here is the basic matrix you should remember:
  358.  
  359.  
  360.  
  361.  
  362.  
  363.  
  364.  
  365.  
  366.  
  367.  
  368.  
  369.  
  370.  
  371.  
  372.  
  373.  
  374.  
  375.  
  376.  
  377.  
  378. IBM PC Assembly Language Tutorial                                         6
  379.  
  380.  
  381.  
  382.          Two operands:          One operand:
  383.           R <-- M                R
  384.           M <-- R                M
  385.           R <-- R                S *
  386.           R|M <-- I
  387.           R|M <-- S  *
  388.           S <-- R|M  *
  389.  
  390.       * -- data moving instructions (MOV, PUSH, POP) only
  391.       S -- segment register (CS, DS, ES, SS)
  392.       R -- ordinary register (AX, BX, CX, DX, SI, DI, BP, SP,
  393.                               AH, AL, BH, BL, CH, CL, DH, DL)
  394.       M -- one of the following
  395.                pure address
  396.                [BX]+offset
  397.                [BP]+offset
  398.                any of the above indexed by SI
  399.                any of the first three indexed by DI
  400.  
  401. 4.  Of course, you want to learn the operations themselves.  As I've sug-
  402.     gested, you want to learn the op codes as the assembler presents them,
  403.     not as the CPU machine language presents them.  So, even though there
  404.     are many MOV op codes you don't need to learn them.  Basically, here is
  405.     the instruction set:
  406.  
  407.     a.  Ordinary two operand instructions.  These instructions perform an
  408.         operation and leave the result in place of one of the operands.
  409.         They are
  410.  
  411.         1)  ADD and ADC -- addition, with or without including a carry from
  412.             a previous addition
  413.  
  414.         2)  SUB and SBB -- subtraction, with or without including a borrow
  415.             from a previous subtraction
  416.  
  417.         3)  CMP -- compare.  It is useful to think of this as a subtraction
  418.             with the answer being thrown away and neither operand actually
  419.             changed
  420.  
  421.         4)  AND, OR, XOR -- typical boolean operations
  422.  
  423.         5)  TEST -- like an AND, except the answer is thrown away and nei-
  424.             ther operand is changed.
  425.  
  426.         6)  MOV -- move data from source to target
  427.  
  428.         7)  LDS, LES, LEA -- some specialized forms of MOV with side
  429.             effects
  430.  
  431.     b.  Ordinary one operand instructions.  These can take any of the oper-
  432.         and forms described above.  Usually, the perform the operation and
  433.         leave the result in the stated place:
  434.  
  435.         1)  INC -- increment contents
  436.  
  437.  
  438.  
  439. IBM PC Assembly Language Tutorial                                         7
  440.  
  441.  
  442.  
  443.         2)  DEC -- decrement contents
  444.  
  445.         3)  NEG -- twos complement
  446.  
  447.         4)  NOT -- ones complement
  448.  
  449.         5)  PUSH -- value goes on stack (operand location itself unchanged)
  450.  
  451.         6)  POP -- value taken from stack, replaces current value
  452.  
  453.     c.  Now you touch on some instructions which do not follow the general
  454.         operand rules but which require the use of certain registers.  The
  455.         important ones are
  456.  
  457.         1)  The multiply and divide instructions
  458.  
  459.         2)  The "adjust" instructions which help in performing arithmetic
  460.             on ASCII or packed decimal data
  461.  
  462.         3)  The shift and rotate instructions.  These have a restriction on
  463.             the second operand:  it must either be the immediate value 1 or
  464.             the contents of the CL register.
  465.  
  466.         4)  IN and OUT which send or receive data from one of the 1024
  467.             hardware ports.
  468.  
  469.         5)  CBW and CWD -- convert byte to word or word to doubleword by
  470.             sign extension
  471.  
  472.     d.  Flow of control instructions.  These deserve study in themselves
  473.         and we will discuss them a little more.  They include
  474.  
  475.         1)  CALL, RET -- call and return
  476.  
  477.         2)  INT, IRET -- interrupt and return-from-interrupt
  478.  
  479.         3)  JMP -- jump or "branch"
  480.  
  481.         4)  LOOP, LOOPNZ, LOOPZ -- special (and useful) instructions which
  482.             implement a counted loop similar to the 370 BCT instruction
  483.  
  484.         5)  various conditional jump instructions
  485.  
  486.     e.  String instructions.  These implement a limited storage-to-storage
  487.         instruction subset and are quite powerful.  All of them have the
  488.         property that
  489.  
  490.         1)  The source of data is described by the combination DS and SI.
  491.  
  492.         2)  The destination of data is described by the combination ES and
  493.             DI.
  494.  
  495.         3)  As part of the operation, the SI and/or DI register(s) is(are)
  496.             incremented or decremented so the operation can be repeated.
  497.  
  498.  
  499.  
  500. IBM PC Assembly Language Tutorial                                         8
  501.  
  502.  
  503.  
  504.         They include
  505.  
  506.         1)  CMPSB/CMPSW -- compare byte or word
  507.  
  508.         2)  LODSB/LODSW -- load byte or word into AL or AX
  509.  
  510.         3)  STOSB/STOSW -- store byte or word from AL or AX
  511.  
  512.         4)  MOVSB/MOVSW -- move byte or word
  513.  
  514.         5)  SCASB/SCASW -- compare byte or word with contents of AL or AX
  515.  
  516.         6)  REP/REPE/REPNE -- a prefix which can be combined with any of
  517.             the above instructions to make them execute repeatedly across a
  518.             string of data whose length is held in CX.
  519.  
  520.     f.  Flag instructions: CLI, STI, CLD, STD, CLC, STC.  These can set or
  521.         clear the interrupt (enabled) direction (for string operations) or
  522.         carry flags.
  523.  
  524.     The addressing summary and the instruction summary given above masks a
  525.     lot of annoying little exceptions.  For example, you can't POP CS, and
  526.     although the R <-- M form of LES is legal, the M <-- R form isn't etc.
  527.     etc.  My advice is
  528.  
  529.     a.  Go for the general rules
  530.  
  531.     b.  Don't try to memorize the exceptions
  532.  
  533.     c.  Rely on common sense and the assembler to teach you about
  534.         exceptions over time.  A lot of the exceptions cover things you
  535.         wouldn't want to do anyway.
  536.  
  537. 5.  A few instructions are rich enough and useful enough to warrent careful
  538.     study.  Here are a few final study guidelines:
  539.  
  540.     a.  It is well worth the time learning to use the string instruction
  541.         set effectively.  Among the most useful are
  542.  
  543.                 REP MOVSB           ;moves a string
  544.                 REP STOSB           ;initializes memory
  545.                 REPNE SCASB         ;look up occurance of character in string
  546.                 REPE CMPSB          ;compare two strings
  547.  
  548.     b.  Similarly, if you have never written for a stack machine before,
  549.         you will need to exercise PUSH and POP and get very comfortable
  550.         with them because they are going to be good friends.  If you are
  551.         used to the 370, with lots of general purpose registers, you may
  552.         find yourself feeling cramped at first, with many fewer registers
  553.         and many instructions having register restrictions.  But, you have
  554.         a hidden ally:  you need a register and you don't want to throw
  555.         away what's in it?  Just PUSH it, and when you are done, POP it
  556.         back.  This can lead to abuse.  Never have more than two
  557.         "expedient" PUSHes in effect and never leave something PUSHed
  558.         across a major header comment or for more than 15 instructions or
  559.  
  560.  
  561. IBM PC Assembly Language Tutorial                                         9
  562.  
  563.  
  564.  
  565.         so.  An exception is the saving and restoring of registers at
  566.         entrance to and exit from a subroutine; here, if the subroutine is
  567.         long, you should probably PUSH everything which the caller may need
  568.         saved, whether you will use the register or not, and POP it in
  569.         reverse order at the end.
  570.  
  571.         Be aware that CALL and INT push return address information on the
  572.         stack and RET and IRET pop it off.  It is a good idea to become
  573.         familiar with the structure of the stack.
  574.  
  575.     c.  In practice, to invoke system services you will use the INT
  576.         instruction.  It is quite possible to use this instruction effec-
  577.         tively in a cookbook fashion without knowing precisely how it
  578.         works.
  579.  
  580.     d.  The transfer of control instructions (CALL, RET, JMP) deserve care-
  581.         ful study to avoid confusion.  You will learn that these can be
  582.         classified as follows:
  583.  
  584.         1)  all three have the capability of being either NEAR (CS register
  585.             unchanged) or FAR (CS register changed)
  586.  
  587.         2)  JMPs and CALLs can be DIRECT (target is assembled into instruc-
  588.             tion) or INDIRECT (target fetched from memory or register)
  589.  
  590.         3)  if NEAR and DIRECT, a JMP can be SHORT (less than 128 bytes
  591.             away) or LONG
  592.  
  593.         In general, the third issue is not worth worrying about.  On a for-
  594.         ward jump which is clearly VERY short, you can tell the assembler
  595.         it is short and save one byte of code:
  596.  
  597.                    JMP SHORT  CLOSEBY
  598.  
  599.         On a backward jump, the assembler can figure it out for you.  On a
  600.         forward jump of dubious length, let the assembler default to a LONG
  601.         form; at worst you waste one byte.
  602.  
  603.         Also leave the assembler to worry about how the target address is
  604.         to be represented, in absolute form or relative form.
  605.  
  606.     e.  The conditional jump set is rather confusing when studied apart
  607.         from the assembler, but you do need to get a feeling for it.  The
  608.         interactions of the sign, carry, and overflow flags can get your
  609.         mind stuttering pretty fast if you worry about it too much.  What
  610.         is boils down to, though, is
  611.  
  612.                 JZ        means what it says
  613.                 JNZ       means what it says
  614.                 JG reater this means "if the SIGNED difference is positive"
  615.                 JA bove   this means "if the UNSIGNED difference is positive"
  616.                 JL ess    this means "if the SIGNED difference is negative"
  617.                 JB elow   this means "if the UNSIGNED difference is negative"
  618.                 JC arry   assembles the same as JB; it's an aesthetic choice
  619.  
  620.  
  621.  
  622. IBM PC Assembly Language Tutorial                                        10
  623.  
  624.  
  625.  
  626.         You should understand that all conditional jumps are inherently
  627.         DIRECT, NEAR, and "short"; the "short" part means that they can't
  628.         go more than 128 bytes in either direction.  Again, this is some-
  629.         thing you could easily imagine to be more of a problem than it is.
  630.         I follow this simple approach:
  631.  
  632.         1)  When taking an abnormal exit from a block of code, I always use
  633.             an unconditional jump.  Who knows how far you are going to end
  634.             up jumping by the time the program is finished.  For example, I
  635.             wouldn't code this:
  636.  
  637.                    TEST     AL,IDIBIT       ;Is the idiot bit on?
  638.                    JNZ      OYVEY           ;Yes.  Go to general cleanup
  639.  
  640.             Rather, I would probably code this:
  641.  
  642.                    TEST     AL,IDIBIT       ;Is the idiot bit on?
  643.                    JZ       NOIDIOCY        ;No.  I am saved.
  644.                    JMP      OYVEY           ;Yes.  What can we say...
  645.               NOIDIOCY:
  646.  
  647.             The latter, of course, is a jump around a jump.  Some would say
  648.             it is evil, but I submit it is hard to avoid in this language.
  649.  
  650.         2)  Otherwise, within a block of code, I use conditional jumps
  651.             freely.  If the block eventually grows so long that the assem-
  652.             bler starts complaining that my conditional jumps are too long
  653.             I
  654.  
  655.             a)  consider reorganizing the block but
  656.  
  657.             b)  also consider changing some conditional jumps to their
  658.                 opposite and use the "jump around a jump" approach as shown
  659.                 above.
  660.  
  661.     Enough about specific instructions!
  662.  
  663. 6.  Finally, in order to use the assembler effectively, you need to know
  664.     the default rules for which segment registers are used to complete
  665.     addresses in which situations.
  666.  
  667.     a.  CS is used to complete an address which is the target of a NEAR
  668.         DIRECT jump.  On an NEAR INDIRECT jump, DS is used to fetch the
  669.         address from memory but then CS is used to complete the address
  670.         thus fetched.  On FAR jumps, of course, CS is itself altered.  The
  671.         instruction counter is always implicitly pointing in the code seg-
  672.         ment.
  673.  
  674.     b.  SS is used to complete an address if BP is used in its formation.
  675.         Otherwise, DS is always used to complete a data address.
  676.  
  677.     c.  On the string instructions, the target is always formed from ES and
  678.         DI.  The source is normally formed from DS and SI.  If there is a
  679.         segment prefix, it overrides the source not the target.
  680.  
  681.  
  682.  
  683. IBM PC Assembly Language Tutorial                                        11
  684.  
  685.  
  686.  
  687. Learning about DOS
  688. __________________
  689. Learning about DOS
  690. Learning about DOS
  691. Learning about DOS
  692.  
  693.  
  694. I think the best way to learn about DOS internals is to read the technical
  695. appendices in the manual.  These are not as complete as we might wish, but
  696. they really aren't bad; I certainly have learned a lot from them.  What you
  697. don't learn from them you might eventually learn via judicious disassembly
  698. of parts of DOS, but that shouldn't really be necessary.
  699.  
  700. From reading the technical appendices, you learn that interrupts 20H
  701. through 27H are used to communicate with DOS.  Mostly, you will use inter-
  702. rupt 21H, the DOS function manager.
  703.  
  704. The function manager implements a great many services.  You request the
  705. individual services by means of a function code in the AH register.  For
  706. example, by putting a nine in the AH register and issuing interrupt 21H you
  707. tell DOS to print a message on the console screen.
  708.  
  709. Usually, but by no means always, the DX register is used to pass data for
  710. the service being requested.  For example, on the print message service
  711. just mentioned, you would put the 16 bit address of the message in the DX
  712. register.  The DS register is also implicitly part of this argument, in
  713. keeping with the universal segmentation rules.
  714.  
  715. In understanding DOS functions, it is useful to understand some history and
  716. also some of the philosophy of MS-DOS with regard to portability.  General-
  717. ly, you will find, once you read the technical information on DOS and also
  718. the IBM technical reference, you will know more than one way to do almost
  719. anything.  Which is best?  For example, to do asynch adapter I/O, you can
  720. use the DOS calls (pretty incomplete), you can use BIOS, or you can go
  721. directly to the hardware.  The same thing is true for most of the other
  722. primitive I/O (keyboard or screen) although DOS is more likely to give you
  723. added value in these areas.  When it comes to file I/O, DOS itself offers
  724. more than one interface.  For example, there are four calls which read data
  725. from a file.
  726.  
  727. The way to decide rationally among these alternatives is by understanding
  728. the tradeoffs of functionality versus portability.  Three kinds of porta-
  729. bility need to be considered:  machine portability, operating system porta-
  730. bility (for example, the ability to assemble and run code under CP/M 86)
  731. and DOS version portability (the ability for a program to run under older
  732. versions of DOS>.
  733.  
  734. Most of the functions originally offered in DOS 1.0 were direct descendents
  735. of CP/M functions; there is even a compatibility interface so that programs
  736. which have been translated instruction for instruction from 8080 assembler
  737. to 8086 assembler might have a reasonable chance of running if they use
  738. only the core CP/M function set.  Among the most generally useful in this
  739. original compatibility set are
  740.  
  741.  
  742.  
  743.  
  744.  
  745.  
  746.  
  747.  
  748. IBM PC Assembly Language Tutorial                                        12
  749.  
  750.  
  751.  
  752.   09   --  print a full message on the screen
  753.   0A   --  get a console input line with full DOS editing
  754.   0F   --  open a file
  755.   10   --  close a file (really needed only when writing)
  756.   11   --  find first file matching a pattern
  757.   12   --  find next file matching a pattern
  758.   13   --  erase a file
  759.   16   --  create a file
  760.   17   --  rename a file
  761.   1A   --  set disk transfer address
  762.  
  763. The next set provide no function above what you can get with BIOS calls or
  764. more specialized DOS calls.  However, they are preferable to BIOS calls
  765. when portability is an issue.
  766.  
  767.   00   --  terminate execution
  768.   01   --  read keyboard character
  769.   02   --  write screen character
  770.   03   --  read COM port character
  771.   04   --  write COM port character
  772.   05   --  print a character
  773.   06   --  read keyboard or write screen with no editing
  774.  
  775. The standard file I/O calls are inferior to the specialized DOS calls but
  776. have the advantage of making the program easier to port to CP/M style sys-
  777. tems.  Thus they are worth mentioning:
  778.  
  779.   14   --  sequential read from file
  780.   15   --  sequential write to file
  781.   21   --  random read from file
  782.   22   --  random write to file
  783.   23   --  determine file size
  784.   24   --  set random record
  785.  
  786. In addition to the CP/M compatible services, DOS also offers some special-
  787. ized services which have been available in all releases of DOS.  These
  788. include
  789.  
  790.   27   --  multi-record random read.
  791.   28   --  multi-record random write.
  792.   29   --  parse filename
  793.   2A-2D -- get and set date and time
  794.  
  795. All of the calls mentioned above which have anything to do with files make
  796. use of a data area called the "FILE CONTROL BLOCK" (FCB).  The FCB is any-
  797. where from 33 to 37 bytes long depending on how it is used.  You are
  798. responsible for creating an FCB and filling in the first 12 bytes, which
  799. contain a drive code, a file name, and an extension.
  800.  
  801. When you open the FCB, the system fills in the next 20 bytes, which
  802. includes a logical record length.  The initial lrecl is always 128 bytes,
  803. to achieve CP/M compatibility.  The system also provides other useful
  804. information such as the file size.
  805.  
  806.  
  807.  
  808.  
  809. IBM PC Assembly Language Tutorial                                        13
  810.  
  811.  
  812.  
  813. After you have opened the FCB, you can change the logical record length.
  814. If you do this, your program is no longer CP/M compatible, but that doesn't
  815. make it a bad thing to do.  DOS documentation suggests you use a logical
  816. record length of one for maximum flexibility.  This is usually a good
  817. recommendation.
  818.  
  819. To perform actual I/O to a file, you eventually need to fill in byte 33 or
  820. possibly bytes 34-37 of the FCB.  Here you supply information about the
  821. record you are interested in reading or writing.  For the most part, this
  822. part of the interface is compatible with CP/M.
  823.  
  824. In general, you do not need to (and should not) modify other parts of the
  825. FCB.
  826.  
  827. The FCB is pretty well described in appendix E of the DOS manual.
  828.  
  829. Beginning with DOS 2.0, there is a whole new system of calls for managing
  830. files which don't require that you build an FCB at all.  These calls are
  831. quite incompatible with CP/M and also mean that your program cannot run
  832. under older releases of DOS.  However, these calls are very nice and easy
  833. to use.  They have these characteristics
  834.  
  835. 1.  To open, create, delete, or rename a file, you need only a character
  836.     string representing its name.
  837.  
  838. 2.  The open and create calls return a 16 bit value which is simply placed
  839.     in the BX register on subsequent calls to refer to the file.
  840.  
  841. 3.  There is not a separate call required to specify the data buffer.
  842.  
  843. 4.  Any number of bytes can be transfered on a single call; no data area
  844.     must be manipulated to do this.
  845.  
  846. The "new" DOS calls also include comprehensive functions to manipulate the
  847. new chained directory structure and to allocate and free memory.
  848.  
  849.  
  850.  
  851. Learning the assembler
  852. ______________________
  853. Learning the assembler
  854. Learning the assembler
  855. Learning the assembler
  856.  
  857.  
  858. It is my feeling that many people can teach themselves to use the assembler
  859. by reading the MACRO Assembler manual if
  860.  
  861. 1.  You have read and understood a book like Morse and thus have a feeling
  862.     for the instruction set
  863.  
  864. 2.  You know something about DOS services and so can communicate with the
  865.     keyboard and screen and do something marginally useful with files.  In
  866.     the absence of this kind of knowledge, you can't write meaningful prac-
  867.     tice programs and so will not progress.
  868.  
  869. 3.  You have access to some good examples (the ones supplied with the
  870.     assembler are not good, in my opinion.  I will try to supply you with
  871.     some more relevant ones.
  872.  
  873.  
  874. IBM PC Assembly Language Tutorial                                        14
  875.  
  876.  
  877.  
  878. 4.  You ignore the things which are most confusing and least useful.  Some
  879.     of the most confusing aspects of the assembler include the facilities
  880.     combining segments.  But, you can avoid using all but the simplest of
  881.     these facilities in many cases, even while writing quite substantial
  882.     applications.
  883.  
  884. 5.  The easiest kind of assembler program to write is a COM program.  They
  885.     might seem harder, at first, then EXE programs because there is an
  886.     extra step involved in creating the executable file, but COM programs
  887.     are structurally very much simpler.
  888.  
  889. At this point, it is necessary to talk about COM programs and EXE programs.
  890. As you probably know, DOS supports two kinds of executable files.  EXE pro-
  891. grams are much more general, can contain many segments, and are generally
  892. built by compilers and sometimes by the assembler.  If you follow the lead
  893. given by the samples distributed with the assembler, you will end up with
  894. EXE programs.  A COM program, in contrast, always contains just one
  895. segment, and receives control with all four segment registers containing
  896. the same value.  A COM program, thus, executes in a simplified environment,
  897. a 64K address space.  You can go outside this address space simply by tem-
  898. porarily changing one segment register, but you don't have to, and that is
  899. the thing which makes COM programs nice and simple.  Let's look at a very
  900. simple one.
  901.  
  902. The classic text on writing programs for the C language says that the first
  903. thing you should write is a program which says
  904.  
  905.       HELLO, WORLD.
  906.  
  907. when invoked.  What's sauce for C is sauce for assembler, so let's start
  908. with a HELLO program of our own.  My first presentation of this will be
  909. bare bones, not stylistically complete, but just an illustration of what an
  910. assembler program absolutely has to have:
  911.  
  912. HELLO  SEGMENT                  ;Set up HELLO code and data section
  913.        ASSUME CS:HELLO,DS:HELLO ;Tell assembler about conditions at entry
  914.        ORG  100H                ;A .COM program begins with 100H byte prefix
  915. MAIN:  JMP  BEGIN               ;Control must start here
  916. MSG    DB   'Hello, world.$'    ;But it is generally useful to put data first
  917. BEGIN: MOV  DX,OFFSET MSG       ;Let DX --> message.
  918.        MOV  AH,9                ;Set DOS function code for printing a message
  919.        INT  21H                 ;Invoke DOS
  920.        RET                      ;Return to system
  921. HELLO  ENDS                     ;End of code and data section
  922.         END  MAIN                 ;Terminate assembler and specify entry point
  923.  
  924.  
  925. First, let's attend to some obvious points.  The macro assembler uses the
  926. general form
  927.  
  928.    name    opcode    operands
  929.  
  930. Unlike the 370 assembler, though, comments are NOT set off from operands by
  931. blanks.  The syntax uses blanks as delimiters within the operand field (see
  932. line 6 of the example) and so all comments must be set off by semi-colons.
  933.  
  934.  
  935. IBM PC Assembly Language Tutorial                                        15
  936.  
  937.  
  938.  
  939. Line comments are frequently set off with a semi-colon in column 1.  I use
  940. this approach for block comments too, although there is a COMMENT statement
  941. which can be used to introduce a block comment.
  942.  
  943. Being an old 370 type, I like to see assembler code in upper case, although
  944. my comments are mixed case.  Actually, the assembler is quite happy with
  945. mixed case anywhere.
  946.  
  947. As with any assembler, the core of the opcode set consists of opcodes which
  948. generate machine instructions but there are also opcodes which generate
  949. data and ones which function as instructions to the assembler itself, some-
  950. times called pseudo-ops.  In the example, there are five lines which gener-
  951. ate machine code (JMP, MOV, MOV, INT, RET), one line which generates data
  952. (DB) and five pseudo-ops (SEGMENT, ASSUME, ORG, ENDS, and END).
  953.  
  954. We will discuss all of them.
  955.  
  956. Now, about labels.  You will see that some labels in the example end in a
  957. colon and some don't.  This is just a bit confusing at first, but no real
  958. mystery.  If a label is attached to a piece of code (as opposed to data),
  959. then the assembler needs to know what to do when you JMP to or CALL that
  960. label.  By convention, if the label ends in a colon, the assembler will use
  961. the NEAR form of JMP or CALL.  If the label does not end in a colon, it
  962. will use the FAR form.  In practice, you will always use the colon on any
  963. label you are jumping to inside your program because such jumps are always
  964. NEAR; there is no reason to use a FAR jump within a single code section.  I
  965. mention this, though, because leaving off the colon isn't usually trapped
  966. as a syntax error, it will generally cause something more abstruse to go
  967. wrong.
  968.  
  969. On the other hand, a label attached to a piece of data or a pseudo-op never
  970. ends in a colon.
  971.  
  972. Machine instructions will generally take zero, one or two operands.  Where
  973. there are two operands, the one which receives the result goes on the left
  974. as in 370 assembler.
  975.  
  976. I tried to explain this before, now maybe it will be even clearer:  there
  977. are many more 8086 machine opcodes then there are assembler opcodes to rep-
  978. resent them.  For example, there are five kinds of JMP, four kinds of CALL,
  979. two kinds of RET, and at least five kinds of MOV depending on how you count
  980. them.  The macro assembler makes a lot of decisions for you based on the
  981. form taken by the operands or on attributes assigned to symbols elsewhere
  982. in your program.  In the example above, the assembler will generate the
  983. NEAR DIRECT form of JMP because the target label BEGIN labels a piece of
  984. code instead of a piece of data (this makes the JMP DIRECT) and ends in a
  985. colon (this makes the JMP NEAR).  The assembler will generate the immediate
  986. forms of MOV because the form OFFSET MSG refers to immediate data and
  987. because 9 is a constant.  The assembler will generate the NEAR form of RET
  988. because that is the default and you have not told it otherwise.
  989.  
  990. The DB (define byte) pseudo-op is an easy one:  it is used to put one or
  991. more bytes of data into storage.  There is also a DW (define word)
  992. pseudo-op and a  DD (define doubleword) pseudo-op;  in the PC MACRO assem-
  993. bler, the fact that a label refers to a byte of storage, a word of storage,
  994.  
  995.  
  996. IBM PC Assembly Language Tutorial                                        16
  997.  
  998.  
  999.  
  1000. or a doubleword of storage can be very significant in ways which we will
  1001. see presently.
  1002.  
  1003. About that OFFSET operator, I guess this is the best way to make the point
  1004. about how the assembler decides what instruction to assemble:  an analogy
  1005. with 370 assembler:
  1006.  
  1007.   PLACE    DC   ......
  1008.            ...
  1009.            LA   R1,PLACE
  1010.            L    R1,PLACE
  1011.  
  1012. In 370 assembler, the first instruction puts the address of label PLACE in
  1013. register 1, the second instruction puts the contents of storage at label
  1014. PLACE in register 1.  Notice that two different opcodes are used.  In the
  1015. PC assembler, the analogous instructions would be
  1016.  
  1017.   PLACE    DW   ......
  1018.            ...
  1019.            MOV  DX,OFFSET PLACE
  1020.            MOV  DX,PLACE
  1021.  
  1022. If PLACE is the label of a word of storage, then the second instruction
  1023. will be understood as a desire to fetch that data into DX.  If X is a
  1024. label, then "OFFSET X" means "the ordinary number which represents X's off-
  1025. set from the start of the segment."  And, if the assembler sees an ordinary
  1026. number, as opposed to a label, it uses the instruction which is equivalent
  1027. to LA.
  1028.  
  1029. If PLACE were the label of a DB pseudo-op, instead of a DW, then
  1030.  
  1031.            MOV  DX,PLACE
  1032.  
  1033. would be illegal.  The assembler worries about length attributes of its
  1034. operands.
  1035.  
  1036. Next, numbers and constants in general.  The assembler's default radix is
  1037. decimal.  You can change this, but I don't recommend it.  If you want to
  1038. represent numbers in other forms of notation such as hex or bit, you gener-
  1039. ally use a trailing letter.  For example,
  1040.  
  1041.            21H
  1042.   is hexidecimal 21,
  1043.            00010000B
  1044.   is the eight bit binary number pictured.
  1045.  
  1046. The next elements we should point to are the SEGMENT...ENDS pair and the
  1047. END instruction.  Every assembler program has to have these elements.
  1048.  
  1049. SEGMENT tells the assembler you are starting a section of contiguous mate-
  1050. rial (code and/or data).  The symmetrically named ENDS statement tells the
  1051. assembler you are finished with a section of contiguous material.  I wish
  1052. they didn't use the word SEGMENT in this context.  To me, a "segment" is a
  1053. hardware construct:  it is the 64K of real storage which becomes address-
  1054. able by virtue of having a particular value in a segment register.  Now, it
  1055.  
  1056.  
  1057. IBM PC Assembly Language Tutorial                                        17
  1058.  
  1059.  
  1060.  
  1061. is true that the "segments" you make with the assembler often correspond to
  1062. real hardware "segments" at execution time.  But, if you look at things
  1063. like the GROUP and CLASS options supported by the linker, you will discover
  1064. that this correspondence is by no means exact.  So, at risk of maybe con-
  1065. fusing you even more, I am going to use the more informal term "section" to
  1066. refer to the area set off by means of the SEGMENT and ENDS instructions.
  1067.  
  1068. The sections delimited by SEGMENT...ENDS pairs are really a lot like CSECTs
  1069. and DSECTs in the 370 world.
  1070.  
  1071. I strongly recommend that you be selective in your study of the SEGMENT
  1072. pseudo-op as described in the manual.  Let me just touch on it here.
  1073.  
  1074.   name     SEGMENT
  1075.   name     SEGMENT  PUBLIC
  1076.   name     SEGMENT  AT  nnn
  1077.  
  1078. Basically, you can get away with just the three forms given above.  The
  1079. first form is what you use when you are writing a single section of assem-
  1080. bler code which will not be combined with other pieces of code at link
  1081. time.   The second form says that this assembly only contains part of the
  1082. section;  other parts might be assembled separately and combined later by
  1083. the linker.
  1084.  
  1085. I have found that one can construct reasonably large modular applications
  1086. in assembler by simply making every assembly use the same segment name and
  1087. declaring the name to be PUBLIC each time.  If you read the assembler and
  1088. linker documentation, you will also be bombarded by information about more
  1089. complex options such as the GROUP statement and the use of other "combine
  1090. types" and "classes."  I don't recommend getting into any of that.  I will
  1091. talk more about the linker and modular construction of programs a little
  1092. later.  The assembler manual also implies that a STACK segment is required.
  1093. This is not really true.  There are numerous ways to assure that you have a
  1094. valid stack at execution time.
  1095.  
  1096. Of course, if you plan to write applications in assembler which are more
  1097. than 64K in size, you will need more than what I have told you; but who is
  1098. really going to do that?  Any application that large is likely to be coded
  1099. in a higher level language.
  1100.  
  1101. The third form of the SEGMENT statement makes the delineated section into
  1102. something like a "DSECT;" that is, it doesn't generate any code, it just
  1103. describes what is present somewhere already in the computer's memory.
  1104. Sometimes the AT value you give is meaningful.  For example, the BIOS work
  1105. area is located at location 40 hex.  So, you might see
  1106.  
  1107.   BIOSAREA  SEGMENT AT 40H      ;Map BIOS work area
  1108.             ORG  BIOSAREA+10H
  1109.   EQUIP     DB   ?              ;Location of equipment flags, first byte
  1110.   BIOSAREA  ENDS
  1111.  
  1112. in a program which was interested in mucking around in the BIOS work area.
  1113.  
  1114. At other times, the AT value you give may be arbitrary, as when you are
  1115. mapping a repeated control block:
  1116.  
  1117.  
  1118. IBM PC Assembly Language Tutorial                                        18
  1119.  
  1120.  
  1121.  
  1122.   PROGPREF SEGMENT   AT 0      ;Really a DSECT mapping the program prefix
  1123.            ORG   PROGPREF+6
  1124.   MEMSIZE  DW   ?              ;Size of available memory
  1125.   PROGPREF ENDS
  1126.  
  1127. Really, no matter whether the AT value represents truth or fiction, it is
  1128. your responsibility, not the assembler's, to get set up a segment register
  1129. so that you can really reach the storage in question.   So, you can't say
  1130.  
  1131.          MOV  AL,EQUIP
  1132.  
  1133. unless you first say something like
  1134.  
  1135.          MOV  AX,BIOSAREA   ;BIOSAREA becomes a symbol with value 40H
  1136.          MOV  ES,AX
  1137.          ASSUME ES:BIOSAREA
  1138.  
  1139. Enough about SEGMENT.  The END statement is simple.  It goes at the end of
  1140. every assembly.  When you are assembling a subroutine, you just say
  1141.  
  1142.          END
  1143.  
  1144. but when you are assembling the main routine of a program you say
  1145.  
  1146.         END label
  1147.  
  1148. where 'label' is the place where execution is to begin.
  1149.  
  1150. Another pseudo-op illustrated in the program is ASSUME.  ASSUME is like the
  1151. USING statement in 370 assembler.  However, ASSUME can ONLY refer to seg-
  1152. ment registers.  The assembler uses ASSUME information to decide whether to
  1153. assemble segment override prefixes and to check that the data you are try-
  1154. ing to access is really accessible.  In this case, we can reassure the
  1155. assembler that both the CS and DS registers will address the section called
  1156. HELLO at execution time.  Actually, the SS and ES registers will too, but
  1157. the assembler never needs to make use of this information.
  1158.  
  1159. I guess I have explained everything in the program except that ORG
  1160. pseudo-op.  ORG means the same thing as it does in many assembly languages.
  1161. It tells the assembler to move its location counter to some particular
  1162. address.  In this case, we have asked the assembler to start assembling
  1163. code hex 100 bytes from the start of the section called HELLO instead of at
  1164. the very beginning.  This simply reflects the way COM programs are loaded.
  1165. When a COM program is loaded by the system, the system sets up all four
  1166. segment registers to address the same 64K of storage.  The first 100 hex
  1167. bytes of that storage contains what is called the program prefix; this area
  1168. is described in appendix E of the DOS manual.  Your COM program physically
  1169. begins after this.  Execution begins with the first physical byte of your
  1170. program; that is why the JMP instruction is there.
  1171.  
  1172. Wait a minute, you say, why the JMP instruction at all?  Why not put the
  1173. data at the end?  Well, in a simple program like this I probably could have
  1174. gotten away with that.  However, I have the habit of putting data first and
  1175. would encourage you to do the same because of the way the assembler has of
  1176. assembling different instructions depending on the nature of the operand.
  1177.  
  1178.  
  1179. IBM PC Assembly Language Tutorial                                        19
  1180.  
  1181.  
  1182.  
  1183. Unfortunately, sometimes the different choices of instruction which can
  1184. assemble from a single opcode have different lengths.  If the assembler has
  1185. already seen the data when it gets to the instructions it has a good chance
  1186. of reserving the right number of bytes on the first pass.  If the data is
  1187. at the end, the assembler may not have enough information on the first pass
  1188. to reserve the right number of bytes for the instruction.  Sometimes the
  1189. assembler will complain about this, something like "Forward reference is
  1190. illegal" but at other times, it will make some default assumption.  On the
  1191. second pass, if the assumption turned out to be wrong, it will report what
  1192. is called a "Phase error," a very nasty error to track down.  So get in the
  1193. habit of putting data and equated symbols ahead of code.
  1194.  
  1195. OK.  Maybe you understand the program now.  Let's walk through the steps
  1196. involved in making it into a real COM file.
  1197.  
  1198. 1.  The file should be created with the name HELLO.ASM (actually the name
  1199.     is arbitrary but the extension .ASM is conventional and useful)
  1200.  
  1201. 2.
  1202.  
  1203.       ASM   HELLO,,;
  1204.  
  1205.     (this is just one example of invoking the assembler; it uses the small
  1206.     assembler ASM, it produces an object file and a listing file with the
  1207.     same name as the source file.  I am not going exhaustively into how to
  1208.     invoke the assembler, which the manual goes into pretty well.  I guess
  1209.     this is the first time I mentioned that there are really two
  1210.     assemblers; the small assembler ASM will run in a 64K machine and
  1211.     doesn't support macros.  I used to use it all the time; now that I have
  1212.     a bigger machine and a lot of macro libraries I use the full function
  1213.     assembler MASM.  You get both when you buy the package).
  1214.  
  1215. 3.  If you issue DIR at this point, you will discover that you have
  1216.     acquired HELLO.OBJ (the object code resulting from the assembly) and
  1217.     HELLO.LST (a listing file).  I guess I can digress for a second here
  1218.     concerning the listing file.  It contains TAB characters.  I have found
  1219.     there are two good ways to get it printed and one bad way.  The bad way
  1220.     is to use LPT1: as the direct target of the listing file or to try
  1221.     copying the LST file to LPT1 without first setting the tabs on the
  1222.     printer.  The two good ways are to either
  1223.  
  1224.     a.  direct it to the console and activate the printer with CTRL-PRTSC.
  1225.         In this case, DOS will expand the tabs for you.
  1226.  
  1227.     b.  direct to LPT1: but first send the right escape sequence to LPT1 to
  1228.         set the tabs every eight columns.  I have found that on some early
  1229.         serial numbers of the IBM PC printer, tabs don't work quite right,
  1230.         which forces you to the first option.
  1231.  
  1232. 4.
  1233.  
  1234.           LINK  HELLO;
  1235.  
  1236.     (again, there are lots of linker options but this is the simplest.  It
  1237.     takes HELLO.OBJ and makes HELLO.EXE).  HELLO.EXE?  I thought we were
  1238.  
  1239.  
  1240. IBM PC Assembly Language Tutorial                                        20
  1241.  
  1242.  
  1243.  
  1244.     making a COM program, not an EXE program.  Right.  HELLO.EXE isn't
  1245.     really executable; its just that the linker doesn't know about COM pro-
  1246.     grams.  That requires another utility.  You don't have this utility if
  1247.     you are using DOS 1.0; you have it if you are using DOS 1.1 or DOS 2.0.
  1248.     Oh, by the way, the linker will warn you that you have no stack
  1249.     segment.  Don't worry about it.
  1250.  
  1251. 5.
  1252.  
  1253.           EXE2BIN  HELLO HELLO.COM
  1254.  
  1255.     This is the final step.  It produces the actual program you will exe-
  1256.     cute.  Note that you have to spell out HELLO.COM; for a nominally
  1257.     rational but actually perverse reason, EXE2BIN uses the default exten-
  1258.     sion BIN instead of COM for its output file.  At this point, you might
  1259.     want to erase HELLO.EXE; it looks a lot more useful than it is.
  1260.     Chances are you won't need to recreate HELLO.COM unless you change the
  1261.     source and then you are going to have to redo the whole thing.
  1262.  
  1263. 6.
  1264.  
  1265.           HELLO
  1266.  
  1267.     You type hello, that invokes the program, it says
  1268.  
  1269.           HELLO YOURSELF!!!
  1270.  
  1271.     (oops, what did I do wrong....?)
  1272.  
  1273.  
  1274.  
  1275. What about subroutines?
  1276. _______________________
  1277. What about subroutines?
  1278. What about subroutines?
  1279. What about subroutines?
  1280.  
  1281.  
  1282. I started with a simple COM program because I actually think they are easi-
  1283. er to create than subroutines to be called from high level languages, but
  1284. maybe its really the latter you are interested in.  Here, I think you
  1285. should get comfortable with the assembler FIRST with little exercises like
  1286. the one above and also another one which I will finish up with.
  1287.  
  1288. Next you are ready to look at the interface information for your particular
  1289. language.  You usually find this in some sort of an appendix.  For example,
  1290. the BASIC manual has Appendix C on Machine Language Subroutines.  The
  1291. PASCAL manual buries the information a little more deeply:  the interface
  1292. to a separately compiled routine can be found in the Chapter on Procedures
  1293. and Functions, in a subsection called Internal Calling Conventions.
  1294.  
  1295. Each language is slightly different, but here are what I think are some
  1296. common issues in subroutine construction.
  1297.  
  1298. 1.  NEAR versus FAR?  Most of the time, your language will probably call
  1299.     your assembler routine as a FAR routine.  In this case, you need to
  1300.     make sure the assembler will generate the right kind of return.  You do
  1301.     this with a PROC...ENDP statement pair.  The PROC statement is probably
  1302.  
  1303.  
  1304.  
  1305. IBM PC Assembly Language Tutorial                                        21
  1306.  
  1307.  
  1308.  
  1309.     a good idea for a NEAR routine too even though it is not strictly
  1310.     required:
  1311.  
  1312.               FAR linkage:        |            NEAR linkage:
  1313.                                   |
  1314.     ARBITRARY SEGMENT             |  SPECIFIC  SEGMENT  PUBLIC
  1315.               PUBLIC THENAME      |            PUBLIC THENAME
  1316.               ASSUME CS:ARBITRARY |            ASSUME CS:SPECIFIC,DS:SPECIFIC
  1317.     THENAME   PROC FAR            |            ASSUME ES:SPECIFIC,SS:SPECIFIC
  1318.               ..... code and data |  THENAME   PROC NEAR
  1319.     THENAME   ENDP                |            ..... code and data ....
  1320.     ARBITRARY ENDS                |  THENAME   ENDP
  1321.               END                 |  SPECIFIC  ENDS
  1322.                                   |            END
  1323.  
  1324.  
  1325.     With FAR linkage, it doesn't really matter what you call the segment.
  1326.     you must declare the name by which you will be called in a PUBLIC pseu-
  1327.     do-op and also show that it is a FAR procedure.  Only CS will be ini-
  1328.     tialized to your segment when you are called.  Generally, the other
  1329.     segment registers will continue to point to the caller's segments.
  1330.  
  1331.     With NEAR linkage, you are executing in the same segment as the caller.
  1332.     Therefore, you must give the segment a specific name as instructed by
  1333.     the language manual.  However, you may be able to count on all segment
  1334.     registers pointing to your own segment (sometimes the situation can be
  1335.     more complicated but I cannot really go into all of the details).  You
  1336.     should be aware that the code you write will not be the only thing in
  1337.     the segment and will be physically relocated within the segment by the
  1338.     linker.  However, all OFFSET references will be relocated and will be
  1339.     correct at execution time.
  1340.  
  1341. 2.  Parameters passed on the stack.  Usually, high level languages pass
  1342.     parameters to subroutines by pushing words onto the stack prior to
  1343.     calling you.  What may differ from language to language is the nature
  1344.     of what is pushed (OFFSET only or OFFSET and SEGMENT) and the order in
  1345.     which it is pushed (left to right, right to left within the CALL state-
  1346.     ment).  However, you will need to study the examples to figure out how
  1347.     to retrieve the parameters from the stack.  A useful fact to exploit is
  1348.     the fact that a reference involving the BP register defaults to a ref-
  1349.     erence to the stack segment.  So, the following strategy can work:
  1350.  
  1351.       ARGS     STRUC
  1352.                DW   3 DUP(?)  ;Saved BP and return address
  1353.       ARG3     DW   ?
  1354.       ARG2     DW   ?
  1355.       ARG1     DW   ?
  1356.       ARGS     ENDS
  1357.            ...........
  1358.                PUSH BP                 ;save BP register
  1359.                MOV  BP,SP              ;Use BP to address stack
  1360.                MOV   ...,[BP].ARG2     ;retrieve second argument
  1361.                (etc.)
  1362.  
  1363.  
  1364.  
  1365.  
  1366. IBM PC Assembly Language Tutorial                                        22
  1367.  
  1368.  
  1369.  
  1370.     This example uses something called a structure, which is only available
  1371.     in the large assembler; furthermore, it uses it without allocating it,
  1372.     which is not a well-documented option.  However, I find the above
  1373.     approach generally pleasing.  The STRUC is like a DSECT in that it
  1374.     establishes labels as being offset a certain distance from an arbitrary
  1375.     point; these labels are then used in the body of code by beginning them
  1376.     with a period; the construction ".ARG2" means, basically, " +
  1377.     (ARG2-ARGS)."
  1378.  
  1379.     What you are doing here is using BP to address the stack, accounting
  1380.     for the word where you saved the caller's BP and also for the two words
  1381.     which were pushed by the CALL instruction.
  1382.  
  1383. 3.  How big is the stack?  BASIC only gives you an eight word stack to play
  1384.     with.  On the other hand, it doesn't require you to save any registers
  1385.     except the segment registers.  Other languages give you a liberal
  1386.     stack, which makes things a lot easier.  If you have to create a new
  1387.     stack segment for yourself, the easiest thing is to place the stack at
  1388.     the end of your program and:
  1389.  
  1390.          CLI                      ;suppress interrupts while changing the stack
  1391.          MOV  SSAVE,SS            ;save old SS in local storage (old SP
  1392.                                   ; already saved in BP)
  1393.          MOV  SP,CS               ;switch
  1394.          MOV  SS,SP               ;the
  1395.          MOV  SP,OFFSET STACKTOP  ;stack
  1396.          STI                      ;(maybe)
  1397.  
  1398.     Later, you can reverse these steps before returning to the caller.  At
  1399.     the end of your program, you place the stack itself:
  1400.  
  1401.              DW   128 DUP(?)          ;stack of 128 words (liberal)
  1402.     STACKTOP LABEL WORD
  1403.  
  1404.  
  1405. 4.  Make sure you save and restore those registers required by the caller.
  1406.  
  1407. 5.  Be sure to get the right kind of addressibility.  In the FAR call exam-
  1408.     ple, only CS addresses your segment.  If you are careful with your
  1409.     ASSUME statements the assembler will keep track of this fact and gener-
  1410.     ate CS prefixes when you make data references; however, you might want
  1411.     to do something like
  1412.  
  1413.                     MOV AX,CS      ;get current segment address
  1414.                     MOV DS,AX      ;To DS
  1415.                     ASSUME DS:THISSEG
  1416.  
  1417.     Be sure you keep your ASSUMEs in synch with reality.
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425.  
  1426.  
  1427. IBM PC Assembly Language Tutorial                                        23
  1428.  
  1429.  
  1430.  
  1431. Learning about BIOS and the hardware
  1432. ____________________________________
  1433. Learning about BIOS and the hardware
  1434. Learning about BIOS and the hardware
  1435. Learning about BIOS and the hardware
  1436.  
  1437.  
  1438. You can't do everything with DOS calls.  You may need to learn something
  1439. about the BIOS and about the hardware itself.  In this, the Technical Ref-
  1440. erence is a very good thing to look at.
  1441.  
  1442. The first thing you look at in the Technical Reference, unless you are
  1443. really determined to master the whole ball of wax, is the BIOS listings
  1444. presented in Appendix A. Glory be:  here is the whole 8K of ROM which deals
  1445. with low level hardware support layed out with comments and everything.
  1446.  
  1447. In fact, if you are just interested in learning what BIOS can do for you,
  1448. you just need to read the header comments at the beginning of each section
  1449. of the listing.
  1450.  
  1451. BIOS services are invoked by means of the INT instruction; the BIOS occu-
  1452. pies interrupts 10H through 1FH and also interrupt 5H; actually, of these
  1453. seventeen interrupts, five are used for user exit points or data pointers,
  1454. leaving twelve actual services.
  1455.  
  1456. In most cases, a service deals with a particular hardware interface; for
  1457. example, BIOS interrupt 10H deals with the screen.  As with DOS function
  1458. calls, many BIOS services can be passed a function code in the AH register
  1459. and possible other arguments.
  1460.  
  1461. I am not going to summarize the most useful BIOS features here; you will
  1462. see some examples in the next sample program we will look at.
  1463.  
  1464. The other thing you might want to get into with the Tech reference is the
  1465. description of some hardware options, particularly the asynch adapter,
  1466. which are not well supported in the BIOS.  The writeup on the asynch adapt-
  1467. er is pretty complete.
  1468.  
  1469. Actually, the Tech reference itself is pretty complete and very nice as far
  1470. as it goes.  One thing which is missing from the Tech reference is informa-
  1471. tion on the programmable peripheral chips on the system board.  These
  1472. include
  1473.  
  1474.       the 8259 interrupt controller
  1475.       the 8253 timer
  1476.       the 8237 DMA controller and
  1477.       the 8255 peripheral interface
  1478.  
  1479. To make your library absolutely complete, you should order the INTEL data
  1480. sheets for these beasts.
  1481.  
  1482. I should say, though, that the only I ever found I needed to know about was
  1483. the interrupt controller.  If you happen to have the 8086 Family User's
  1484. Manual, the big book put out by INTEL, which is one of the things people
  1485. sometimes buy to learn about 8086 architecture, there is an appendix there
  1486. which gives an adequate description of the 8259.
  1487.  
  1488.  
  1489.  
  1490.  
  1491.  
  1492. IBM PC Assembly Language Tutorial                                        24
  1493.  
  1494.  
  1495.  
  1496. A final example
  1497. _______________
  1498. A final example
  1499. A final example
  1500. A final example
  1501.  
  1502.  
  1503. I leave you with a more substantial example of code which illustrates some
  1504. good elementary techniques; I won't claim its style is perfect, but I think
  1505. it is adequate.  I think this is a much more useful example than what you
  1506. will get with the assembler:
  1507.  
  1508.           PAGE 61,132
  1509.           TITLE SETSCRN -- Establish correct monitor use at boot time
  1510. ;
  1511. ;         This program is a variation on many which toggle the equipment flags
  1512. ;         to support the use of either video option (monochrome or color).
  1513. ;         The thing about this one is it prompts the user in such a way that he
  1514. ;         can select the use of the monitor he is currently looking at (or which
  1515. ;         is currently connected or turned on) without really having to know
  1516. ;         which is which.  SETSCRN is a good program to put first in an
  1517. ;         AUTOEXEC.BAT file.
  1518. ;
  1519. ;         This program is highly dependent on the hardware and BIOS of the IBMPC
  1520. ;         and is hardly portable, except to very exact clones.  For this reason,
  1521. ;         BIOS calls are used in lieu of DOS function calls where both provide
  1522. ;         equal function.
  1523. ;
  1524.  
  1525.  
  1526. OK.  That's the first page of the program.  Notice the PAGE statement,
  1527. which you can use to tell the assembler how to format the listing.  You
  1528. give it lines per page and characters per line.  I have mine setup to print
  1529. on the host lineprinter; I routinely upload my listings at 9600 baud and
  1530. print them on the host; it is faster than using the PC printer.
  1531.  
  1532. There is also a TITLE statement.  This simply provides a nice title for
  1533. each page of your listing.  Now for the second page:
  1534.  
  1535.           SUBTTL -- Provide .COM type environment and Data
  1536.           PAGE
  1537. ;
  1538. ;         First, describe the one BIOS byte we are interested in
  1539. ;
  1540. BIOSDATA  SEGMENT   AT 40H    ;Describe where BIOS keeps his data
  1541.           ORG       10H       ;Skip parts we are not interested in
  1542. EQUIP     DB        ?         ;Equipment flag location
  1543. MONO      EQU       00110000B ;These bits on if monochrome
  1544. COLOR     EQU       11101111B ;Mask to make BIOS think of the color board
  1545. BIOSDATA  ENDS                ;End of interesting part
  1546. ;
  1547. ;         Next, describe some values for interrupts and functions
  1548. ;
  1549. DOS       EQU       21H       ;DOS Function Handler INT code
  1550. PRTMSG    EQU       09H       ;Function code to print a message
  1551. KBD       EQU       16H       ;BIOS keyboard services INT code
  1552. GETKEY    EQU       00H       ;Function code to read a character
  1553. SCREEN    EQU       10H       ;BIOS Screen services INT code
  1554. MONOINIT  EQU       02H       ;Value to initialize monochrome screen
  1555.  
  1556.  
  1557. IBM PC Assembly Language Tutorial                                        25
  1558.  
  1559.  
  1560.  
  1561. ;COLORINIT EQU       03H       ;Value to initialize color screen (80x25)
  1562. COLORINIT EQU      01H       ;Value to initialize color screen (40X25)
  1563. ;
  1564. ;         Now, describe our own segment
  1565. ;
  1566. SETSCRN   SEGMENT             ;Set operating segment for CODE and DATA
  1567. ;
  1568.           ASSUME CS:SETSCRN,DS:SETSCRN,ES:SETSCRN,SS:SETSCRN    ;All segments
  1569. ;
  1570.           ORG       100H      ;Begin assembly at standard .COM offset
  1571. ;
  1572. MAIN      PROC      NEAR      ;COM files use NEAR linkage
  1573.           JMP       BEGIN     ;And, it is helpful to put the data first, but
  1574. ;                             ;then you must branch around it.
  1575. ;
  1576. ;         Data used in SETSCRN
  1577. ;
  1578. CHANGELOC   DD      EQUIP     ;Location of the EQUIP, recorded as far pointer
  1579. MONOPROMPT  DB      'Please press the plus ( + ) key.$'    ;User sees on mono
  1580. COLORPROMPT DB      'Please press the minus ( - ) key.$'   ;User sees on color
  1581.  
  1582.  
  1583. Several things are illustrated on this page.  First, in addition to titles,
  1584. the assembler supports subtitles:  hence the SUBTTL pseudo-op.  Second, the
  1585. PAGE pseudo-op can be used to go to a new page in the listing.  You see an
  1586. example here of the DSECT-style segment in the "SEGMENT AT 40H".  Here, our
  1587. our interest is in correctly describing the location of some data in the
  1588. BIOS work area which really is located at segment 40H.
  1589.  
  1590. You will also see illustrated the EQU instruction, which just gives a sym-
  1591. bolic name to a number.  I don't make a fetish of giving a name to every
  1592. single number in a program.  I do feel strongly, though, that interrupts
  1593. and function codes, where the number is arbitrary and the function being
  1594. performed is the thing of interest, should always be given symbolic names.
  1595.  
  1596. One last new element in this section is the define doubleword (DD) instruc-
  1597. tion.  A doubleword constant can refer, as in this case, to a location in
  1598. another segment.  The assembler will be happy to use information at its
  1599. disposal to properly assemble it.  In this case, the assembler knows that
  1600. EQUIP is offset 10 in the segment BIOSDATA which is at 40H.
  1601.  
  1602.           SUBTTL -- Perform function
  1603.           PAGE
  1604. BEGIN:    CALL      MONOON                  ;Turn on mono display
  1605.           MOV       DX,OFFSET MONOPROMPT          ;GET MONO PROMPT
  1606.           MOV       AH,PRTMSG                     ;ISSUE
  1607.           INT       DOS                           ;IT
  1608.           CALL      COLORON                 ;Turn on color display
  1609.           MOV       DX,OFFSET COLORPROMPT         ;GET COLOR PROMPT
  1610.           MOV       AH,PRTMSG                     ;ISSUE
  1611.           INT       DOS                           ;IT
  1612.           MOV       AH,GETKEY               ;Obtain user response
  1613.           INT       KBD
  1614.           CMP       AL,'+'                  ;Does he want MONO?
  1615.           JNZ       NOMONO
  1616.  
  1617.  
  1618. IBM PC Assembly Language Tutorial                                        26
  1619.  
  1620.  
  1621.  
  1622.           CALL      MONOON                  ;yes.  give it to him
  1623. NOMONO:   RET
  1624. MAIN      ENDP
  1625.  
  1626.  
  1627. The main code section makes use of subroutines to keep the basic flow sim-
  1628. ple.  About all that's new to you in this section is the use of the BIOS
  1629. interrupt KBD to read a character from the keyboard.
  1630.  
  1631. Now for the subroutines, MONOON and COLORON:
  1632.  
  1633.           SUBTTL -- Routines to turn monitors on
  1634.           PAGE
  1635. MONOON    PROC      NEAR                ;Turn mono on
  1636.           LES       DI,CHANGELOC        ;Get location to change
  1637.           ASSUME    ES:BIOSDATA         ;TELL ASSEMBLER ABOUT CHANGE TO ES
  1638.           OR        EQUIP,MONO
  1639.           MOV       AX,MONOINIT         ;Get screen initialization value
  1640.           INT       SCREEN              ;Initialize screen
  1641.           RET
  1642. MONOON    ENDP
  1643. COLORON   PROC      NEAR                ;Turn color on
  1644.           LES       DI,CHANGELOC        ;Get location to change
  1645.           ASSUME    ES:BIOSDATA         ;TELL ASSEMBLER ABOUT CHANGE TO ES
  1646.           AND       EQUIP,COLOR
  1647.           MOV       AX,COLORINIT        ;Get screen initialization value
  1648.           INT       SCREEN              ;Initialize screen
  1649.           RET
  1650. COLORON   ENDP
  1651. SETSCRN   ENDS                          ;End of segment
  1652.           END       MAIN                ;End of assembly; execution at MAIN
  1653.  
  1654.  
  1655. The instructions LES and LDS are useful ones for dealing with doubleword
  1656. addresses.  The offset is loaded into the operand register and the segment
  1657. into ES (for LES) or DS (for LDS).  By telling the assembler, with an
  1658. ASSUME, that ES now addresses the BIOSDATA segment, it is able to correctly
  1659. assemble the OR and AND instructions which refer to the EQUIP byte.  An ES
  1660. segment prefix is added.
  1661.  
  1662. To understand the action here, you simply need to know that flags in that
  1663. particular byte control how the BIOS screen service initializes the adapt-
  1664. ers.  BIOS will only work with one adapter at a time; by setting the equip-
  1665. ment flags to show one or the other as installed and calling BIOS screen
  1666. initialization, we achieve the desired effect.
  1667.  
  1668. The rest is up to you.
  1669.  
  1670.  
  1671.  
  1672.  
  1673.  
  1674.  
  1675.  
  1676.  
  1677.  
  1678.  
  1679. IBM PC Assembly Language Tutorial                                        27
  1680. 
  1681.  
  1682. 
  1683.  
  1684. The rest is up to you.
  1685.  
  1686.  
  1687.  
  1688.  
  1689.  
  1690.  
  1691.  
  1692.  
  1693.  
  1694.  
  1695. IBM PC Assembly Language Tutorial